'use client';

import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Modal,
  Form,
  message,
  Popconfirm,
  Tooltip,
  Card,
  Row,
  Col,
  Statistic,
  Badge,
  Descriptions,
  Switch
} from 'antd';
import {
  SafetyOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  SettingOutlined,
  EyeOutlined,
  CrownOutlined,
  TeamOutlined,
  KeyOutlined
} from '@ant-design/icons';
import PermissionConfigModal from './components/PermissionConfigModal';
import type { ColumnsType } from 'antd/es/table';
import AdminLayout from '../AdminLayout';
import styles from './Roles.module.scss';

const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;

interface Role {
  id: string;
  name: string;
  display_name: string;
  description?: string;
  level: number;
  is_system: boolean;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  user_count?: number;
  permission_count?: number;
}

interface RoleListResponse {
  success: boolean;
  data: Role[];
  total: number;
  page: number;
  limit: number;
  stats?: {
    total: number;
    active: number;
    system: number;
    custom: number;
  };
}

interface CreateRoleData {
  name: string;
  display_name: string;
  description?: string;
  level: number;
  is_active: boolean;
}

const RolesPage: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [searchText, setSearchText] = useState('');
  const [isSystemFilter, setIsSystemFilter] = useState<string>('');
  const [isActiveFilter, setIsActiveFilter] = useState<string>('');
  const [stats, setStats] = useState<any>(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

  // 获取角色列表
  const fetchRoles = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString(),
        ...(searchText && { search: searchText }),
        ...(isSystemFilter && { is_system: isSystemFilter }),
        ...(isActiveFilter && { is_active: isActiveFilter })
      });

      const response = await fetch(`/api/admin/roles?${params}`);
      const result: RoleListResponse = await response.json();

      if (result.success) {
        setRoles(result.data);
        setTotal(result.total);
        setStats(result.stats);
      } else {
        message.error('获取角色列表失败');
      }
    } catch (error) {
      message.error('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 创建角色
  const handleCreateRole = async (values: CreateRoleData) => {
    try {
      const response = await fetch('/api/admin/roles', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('角色创建成功');
        setCreateModalVisible(false);
        createForm.resetFields();
        fetchRoles();
      } else {
        message.error(result.error || '创建角色失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 更新角色
  const handleUpdateRole = async (values: Partial<Role>) => {
    if (!selectedRole) return;

    try {
      const response = await fetch(`/api/admin/roles/${selectedRole.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const result = await response.json();
      if (result.success) {
        message.success('角色更新成功');
        setEditModalVisible(false);
        editForm.resetFields();
        setSelectedRole(null);
        fetchRoles();
      } else {
        message.error(result.error || '更新角色失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 删除角色
  const handleDeleteRole = async (roleId: string) => {
    try {
      const response = await fetch(`/api/admin/roles/${roleId}`, {
        method: 'DELETE',
      });

      const result = await response.json();
      if (result.success) {
        message.success('角色删除成功');
        fetchRoles();
      } else {
        message.error(result.error || '删除角色失败');
      }
    } catch (error) {
      message.error('网络错误');
    }
  };

  // 配置角色权限
  const handleConfigurePermissions = (role: Role) => {
    setSelectedRole(role);
    setPermissionModalVisible(true);
  };

  // 获取角色级别颜色
  const getLevelColor = (level: number) => {
    if (level >= 90) return 'red';
    if (level >= 70) return 'orange';
    if (level >= 50) return 'blue';
    if (level >= 30) return 'green';
    return 'default';
  };

  // 获取角色级别名称
  const getLevelName = (level: number) => {
    if (level >= 90) return '超级管理员';
    if (level >= 70) return '管理员';
    if (level >= 50) return '高级用户';
    if (level >= 30) return '普通用户';
    return '访客';
  };

  // 表格列定义
  const columns: ColumnsType<Role> = [
    {
      title: '角色名称',
      key: 'role',
      width: 200,
      render: (_, record) => (
        <Space>
          <SafetyOutlined style={{ color: getLevelColor(record.level) }} />
          <div>
            <div className={styles.roleName}>{record.display_name}</div>
            <div className={styles.roleCode}>{record.name}</div>
          </div>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text) => text || '-',
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 120,
      sorter: true,
      render: (level) => (
        <Tag color={getLevelColor(level)}>
          {level} - {getLevelName(level)}
        </Tag>
      ),
    },
    {
      title: '类型',
      dataIndex: 'is_system',
      key: 'is_system',
      width: 100,
      render: (isSystem) => (
        <Tag color={isSystem ? 'blue' : 'green'}>
          {isSystem ? '系统角色' : '自定义'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive) => (
        <Badge 
          status={isActive ? 'success' : 'default'} 
          text={isActive ? '启用' : '禁用'} 
        />
      ),
    },
    {
      title: '用户数',
      dataIndex: 'user_count',
      key: 'user_count',
      width: 100,
      render: (count) => (
        <Space>
          <TeamOutlined />
          {count || 0}
        </Space>
      ),
    },
    {
      title: '权限数',
      dataIndex: 'permission_count',
      key: 'permission_count',
      width: 100,
      render: (count) => (
        <Space>
          <KeyOutlined />
          {count || 0}
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date) => new Date(date).toLocaleString(),
      sorter: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setSelectedRole(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="配置权限">
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
              onClick={() => handleConfigurePermissions(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              disabled={record.is_system}
              onClick={() => {
                setSelectedRole(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个角色吗？"
            description="删除后将无法恢复，请谨慎操作。"
            onConfirm={() => handleDeleteRole(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.is_system}
          >
            <Tooltip title={record.is_system ? '系统角色不能删除' : '删除'}>
              <Button
                type="text"
                size="small"
                danger
                disabled={record.is_system}
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchRoles();
  }, [currentPage, pageSize, searchText, isSystemFilter, isActiveFilter]);

  return (
    <AdminLayout pageTitle="角色管理">
      <div className={styles.rolesPage}>
        {/* 统计卡片 */}
        {stats && (
          <Row gutter={16} className={styles.statsRow}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="总角色数"
                  value={stats.total}
                  prefix={<SafetyOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="启用角色"
                  value={stats.active}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="系统角色"
                  value={stats.system}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="自定义角色"
                  value={stats.custom}
                  prefix={<CrownOutlined />}
                />
              </Card>
            </Col>
          </Row>
        )}

        {/* 搜索和筛选 */}
        <Card className={styles.filterCard}>
          <Row gutter={16} align="middle">
            <Col flex="auto">
              <Space size="middle">
                <Search
                  placeholder="搜索角色名称、描述"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={setSearchText}
                  enterButton={<SearchOutlined />}
                />
                <Select
                  placeholder="类型筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={isSystemFilter}
                  onChange={setIsSystemFilter}
                >
                  <Option value="true">系统角色</Option>
                  <Option value="false">自定义</Option>
                </Select>
                <Select
                  placeholder="状态筛选"
                  allowClear
                  style={{ width: 120 }}
                  value={isActiveFilter}
                  onChange={setIsActiveFilter}
                >
                  <Option value="true">启用</Option>
                  <Option value="false">禁用</Option>
                </Select>
              </Space>
            </Col>
            <Col>
              <Space>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={fetchRoles}
                  loading={loading}
                >
                  刷新
                </Button>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setCreateModalVisible(true)}
                >
                  新增角色
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 角色表格 */}
        <Card>
          <Table<Role>
            columns={columns}
            dataSource={roles}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1400 }}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              onChange: (page, size) => {
                setCurrentPage(page);
                setPageSize(size || 20);
              },
            }}
          />
        </Card>

        {/* 创建角色弹窗 */}
        <Modal
          title={<><PlusOutlined /> 新增角色</>}
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
          }}
          footer={null}
          width={600}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateRole}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="角色标识"
                  rules={[
                    { required: true, message: '请输入角色标识' },
                    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线' }
                  ]}
                >
                  <Input placeholder="如：editor, manager" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                  rules={[{ required: true, message: '请输入显示名称' }]}
                >
                  <Input placeholder="如：编辑者, 管理员" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="description"
              label="角色描述"
            >
              <TextArea rows={3} placeholder="请输入角色描述" />
            </Form.Item>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="level"
                  label="权限级别"
                  rules={[{ required: true, message: '请输入权限级别' }]}
                  initialValue={10}
                >
                  <Select placeholder="请选择权限级别">
                    <Option value={10}>10 - 访客</Option>
                    <Option value={30}>30 - 普通用户</Option>
                    <Option value={50}>50 - 高级用户</Option>
                    <Option value={70}>70 - 管理员</Option>
                    <Option value={90}>90 - 超级管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="is_active"
                  label="启用状态"
                  valuePropName="checked"
                  initialValue={true}
                >
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setCreateModalVisible(false);
                  createForm.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  创建
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 编辑角色弹窗 */}
        <Modal
          title={<><EditOutlined /> 编辑角色</>}
          open={editModalVisible}
          onCancel={() => {
            setEditModalVisible(false);
            editForm.resetFields();
            setSelectedRole(null);
          }}
          footer={null}
          width={600}
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleUpdateRole}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="角色标识"
                  rules={[
                    { required: true, message: '请输入角色标识' },
                    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线' }
                  ]}
                >
                  <Input placeholder="如：editor, manager" disabled={selectedRole?.is_system} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="display_name"
                  label="显示名称"
                  rules={[{ required: true, message: '请输入显示名称' }]}
                >
                  <Input placeholder="如：编辑者, 管理员" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="description"
              label="角色描述"
            >
              <TextArea rows={3} placeholder="请输入角色描述" />
            </Form.Item>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="level"
                  label="权限级别"
                  rules={[{ required: true, message: '请输入权限级别' }]}
                >
                  <Select placeholder="请选择权限级别" disabled={selectedRole?.is_system}>
                    <Option value={10}>10 - 访客</Option>
                    <Option value={30}>30 - 普通用户</Option>
                    <Option value={50}>50 - 高级用户</Option>
                    <Option value={70}>70 - 管理员</Option>
                    <Option value={90}>90 - 超级管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="is_active"
                  label="启用状态"
                  valuePropName="checked"
                >
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                </Form.Item>
              </Col>
            </Row>
            {selectedRole?.is_system && (
              <div style={{ marginBottom: 16, padding: 12, background: '#fff7e6', border: '1px solid #ffd591', borderRadius: 4 }}>
                <Space>
                  <SafetyOutlined style={{ color: '#fa8c16' }} />
                  <span style={{ color: '#fa8c16' }}>系统角色的标识和级别不能修改</span>
                </Space>
              </div>
            )}
            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => {
                  setEditModalVisible(false);
                  editForm.resetFields();
                  setSelectedRole(null);
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 权限配置模态框 */}
        <PermissionConfigModal
          visible={permissionModalVisible}
          role={selectedRole}
          onCancel={() => {
            setPermissionModalVisible(false);
            setSelectedRole(null);
          }}
          onSuccess={() => {
            fetchRoles(); // 刷新角色列表
          }}
        />
      </div>
    </AdminLayout>
  );
};

export default RolesPage;